//
//  MyReminderViewController.m
//  NOAHWM
//
//  Created by Frank on 6/20/13.
//  Copyright (c) 2013 Ryan. All rights reserved.
//

#import "MyReminderViewController.h"
#import "NYMemberCenterDataManager.h"
#import "JSON.h"
#import "NYMyReminder.h"
#import "ListDynamicCell.h"
#import "DynamicDetailViewController.h"

@interface MyReminderViewController ()
@property (nonatomic, retain) NSMutableDictionary *myDict;
@end

@implementation MyReminderViewController

@synthesize reminderListTableView;
@synthesize myRemindList;
@synthesize myDict;
@synthesize placeHolderImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle: @"我的提醒"];
    //[self setLeftNaviItemWithTitle:@"返回" imageName:@"Icon_Back"];
    //[self setRightNaviItemWithTitle:@"保存" imageName:nil];
    /*
    self.cycleScrollView.cycleDelegate = self;
    self.cycleScrollView.delegate = self.cycleScrollView.cycleDelegate;
    [self refreshProductsList];
    */
    [self callServerToGetMyRemind];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reduceReminderList:) name:kMyReminderReduceNotification object:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.reminderListTableView = nil;
    self.myRemindList = nil;
    self.placeHolderImageView = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if (self.isViewLoaded && !self.view.window) {
        self.reminderListTableView = nil;
        self.myRemindList = nil;
        self.placeHolderImageView = nil;
    }
}

- (void)dealloc
{
    [placeHolderImageView release];
    [reminderListTableView release];
    [myRemindList release];
    [super dealloc];
}

#pragma mark - my public methord
- (void)callServerToGetMyRemind
{
    NSString *accountId = [NYMemberCenterDataManager sharedManager].loginMember.accountId;
    [self callServerToGetMyRemindList:accountId  productID:@"" objectType:@"" isNew:@"1" updateTime:@""];
}

- (void)callServerToGetMyRemindList:(NSString *)accountId
                           productID:(NSString *)productID
                         objectType:(NSString *)objectType
                              isNew:(NSString*)isNew
                       updateTime:(NSString *)updateTime
{
    NSString *suburl = [NSString stringWithFormat:kMyReminderUrl,@"jsonp",accountId,productID,objectType,isNew,updateTime];
    suburl = [suburl stringByAppendingString:@"app000045"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}


#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    self.myRemindList = [NSMutableArray array];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        self.reminderListTableView.hidden = NO;
        self.placeHolderImageView.hidden = YES;
        NSArray *array = [dict objectForKey:@"list"];
        for(NSDictionary *dynamicDict in array)
        {
            NYAccountDynamic *nyad = [[NYAccountDynamic alloc] init];
            for(NSString *key in [dynamicDict allKeys])
            {
                id value = [dynamicDict objectForKey:key];
                @try {
                    [nyad setValue:value forKey:key];
                }
                @catch (NSException *exception) {
                    NSLog(@"试图添加不存在的key: %@到NYAccountDynamic实例中.",key);
                }
            }
            NSString *lineTime = nyad.line_time;
            NSDate *lineDate = [NSDate dateFromStringByFormat:@"yyyy-MM-dd" string:lineTime];
            NSString *weekday = [NSDate weekdataForDate:lineDate];
            nyad.dynamicWeekday = weekday;
            
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSDateComponents *component = [calendar components:NSDayCalendarUnit fromDate:lineDate];
            nyad.dynamicDay = [NSString stringWithFormat:@"%d",component.day];
            nyad.dynamicMonth = [NSDate dateToStringByFormat:@"yyyy-MM" date:lineDate];
            [self.myRemindList addObject:nyad];
            [nyad release];
        }

        //
        self.myDict = [NSMutableDictionary dictionary];
        for(NYAccountDynamic *nyad in self.myRemindList)
        {
            
            
                NSString *key = nyad.dynamicMonth;
                NSMutableArray *array = nil;
                if([self.myDict objectForKey:key] == nil)
                {
                    array = [NSMutableArray array];
                    [self.myDict setObject:array forKey:key];
                }
                else
                {
                    array = [self.myDict objectForKey:key];
                }
                [array addObject:nyad];
            
            
        }
        //给所有日期对应的数据降序排序
        for(NSString *key in self.myDict.allKeys)
        {
            NSMutableArray *array = [self.myDict objectForKey:key];
            [array sortUsingComparator:^NSComparisonResult(NYAccountDynamic *dyn1, NYAccountDynamic *dyn2){
                if([dyn1.dynamicDay compare:dyn2.dynamicDay options:NSNumericSearch] == NSOrderedAscending)
                    return NSOrderedDescending;
                else if([dyn1.dynamicDay compare:dyn2.dynamicDay options:NSNumericSearch] == NSOrderedDescending)
                    return NSOrderedAscending;
                else
                    return NSOrderedSame;
            }];
        }

        //重新加载产品列表
        [self.reminderListTableView reloadData];
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
    if([self.myDict allKeys].count == 0)
    {
        self.reminderListTableView.hidden = YES;
        self.placeHolderImageView.hidden = NO;
        self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
    }
    else
    {
        self.reminderListTableView.hidden = NO;
        self.placeHolderImageView.hidden = YES;
    }
}

- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    self.reminderListTableView.hidden = YES;
    self.placeHolderImageView.hidden = NO;
    self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    NSArray *allkeys = [[self.myDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
        if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
            return NSOrderedDescending;
        else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
            return NSOrderedAscending;
        else
            return NSOrderedSame;
    }];

    NSString *key = [allkeys objectAtIndex:section];
    NSArray *array = [self.myDict objectForKey:key];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return [self.myDict allKeys].count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    ListDynamicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"ListDynamicCell" owner:self options:nil];
        cell = [nibs lastObject];
        UIImageView *bgView = [[UIImageView alloc] initWithFrame:cell.bounds];
        bgView.image = [UIImage imageNamed:@"bg_selection@2x.png"];
        cell.selectedBackgroundView = bgView;
        [bgView release];
    }

    NSArray *allkeys = [[self.myDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
        if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
            return NSOrderedDescending;
        else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
            return NSOrderedAscending;
        else
            return NSOrderedSame;
    }];
    NSString *key = [allkeys objectAtIndex:indexPath.section];
    NSArray *array = [self.myDict objectForKey:key];
    NYAccountDynamic *nyad = [array objectAtIndex:indexPath.row];
    cell.nameLabel.text = nyad.fapp_title;
    cell.desLabel.text = nyad.article_info;
    cell.weekdayLabel.text = nyad.dynamicWeekday;
    cell.dayLabel.text = nyad.dynamicDay;
    return cell;
}

#pragma mark - tableview delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.sectionHeaderHeight)];
        sectionView.backgroundColor = [UIColor clearColor];
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:sectionView.bounds];
        bgImageView.image = [UIImage imageNamed:@"bg_dynamicSection@2x.png"];
        [sectionView addSubview:bgImageView];
        [bgImageView release];
        
        NSArray *allkeys = [[self.myDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
            if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
        NSString *key = [allkeys objectAtIndex:section];
        
        UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(15.f, 0, tableView.frame.size.width-30.f, tableView.sectionHeaderHeight)];
        dateLabel.backgroundColor = [UIColor clearColor];
        dateLabel.textColor = [UIColor colorWithRed:28.f/255 green:28.f/255 blue:28.f/255 alpha:1.f];
        dateLabel.font = [UIFont systemFontOfSize:14.f];
        /**
         设置日期
         */
        dateLabel.text = key;
        
        [sectionView addSubview:dateLabel];
        [dateLabel release];
        return [sectionView autorelease];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NYAccountDynamic *nyAD = nil;

    NSArray *allkeys = [[self.myDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *string1, NSString *string2){
            if([string1 compare:string2 options:NSNumericSearch] == NSOrderedAscending)
                return NSOrderedDescending;
            else if([string1 compare:string2 options:NSNumericSearch] == NSOrderedDescending)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
    }];
    NSString *key = [allkeys objectAtIndex:indexPath.section];
    NSArray *array = [self.myDict objectForKey:key];
    nyAD = [array objectAtIndex:indexPath.row];

    DynamicDetailViewController *ddvc = [[DynamicDetailViewController alloc] init];
    ddvc.accountDynamic = nyAD;
    ddvc.isRightMenuEnter = NO;
    [self.navigationController pushViewController:ddvc animated:YES];
    [ddvc release];

}

#pragma mark - notification methord
- (void)reduceReminderList: (NSNotification *)notification
{
    NYDynamicDetail *reductItem = notification.object;
    NSString *article = reductItem.article_id;
    for ( NSString *key in self.myDict) {
        NSMutableArray *arry = [self.myDict objectForKey:key];
        for (NYAccountDynamic* pru in arry) {
            if ([pru.article_id isEqualToString:article]) {
                [arry removeObject:pru];
                break;
            }
        }
    }
    [self.reminderListTableView reloadData];
}
@end
